<template>
	<div class="uploadlist">
		<draggable v-if="imgarray.length>0" :list="imgarray" :animation="100" :forceFallback="true"  @end="onEnd" @change="onMoveCallback" class="imgmove">
		     <transition-group>
		       <div v-for="(item, index) in imgarray" :key="item.id" class="boxsetdelecte" v-if="imgarray.length > 0">
					<b>{{index+1}}</b>
		         <img :src="item.imageUrl" alt="" style="width:200px;border: 1px solid #295cff80;">
				 <span><img src="../../assets/image/school/drag.png" alt="" style="width:24px;height:24px;"></span>
				 <div class="buttonboxedit">
					 <i @click="showViewer(index)">查看</i>
					 <i @click="delecttemplate(item.id)">删除</i>
				 </div>
		       </div>
		     </transition-group>
		   </draggable>
		   <div class="upload-image">
		   		<input type="file" class="fileIndex" multiple @change="handleFileChange" accept="image/*" />
		   		<div class="uploadBoxinfo">
		   			点击上传<i>/</i>扫描图像
		   		</div>
		   </div>
		   <viewer
			 class="viewer"
			 ref="viewer"
			 :images="imgarray"
			 :shown="viewerVisible"
			 @inited="viewerInited"
		   >
			 <template #default="{ images }">
			   <img
				 v-for="(image, index) in images"
				 :key="index"
				 :src="image.imageUrl"
				 style="display: none;"
			   >
			 </template>
		   </viewer>
	</div>
  
</template>

<script>
import { get, post, del, put } from '../../request/api.js'
import draggable from 'vuedraggable';
export default {
  name: 'UploadImage',
  props: {
	modudellist:{
		type: Array,
		default: () => []
	},
	examNoLength:{
		type: Number,
		default: () => ''
	},
	answerCardPages:{
		type: Number,
		default: () => ''
	}
  },
  data() {
    return {
      imageUrl: '',
	  imgarray:[],
	  uploadimagearry:[],
	  viewerVisible: false, // 控制查看器的显示状态
	        viewerIndex: 0, // 当前查看的图片索引
    };
  },
  mounted() {
  	this.examInfo = JSON.parse(sessionStorage.getItem('examInfo'))
	this.modeltab()
  },
    components: {
      draggable,
    },
  methods: {
	  showViewer(index) {
	        // 显示查看器并跳转到指定图片
	        this.$viewer.view(index);
	      },
	      viewerInited(viewer) {
	        // 在 viewer 初始化后，可以通过 this.$viewer 访问 viewer 实例
	        this.$viewer = viewer;
	      },
	  // 获取模板
	  modeltab(){
	  	const url =  `/template/examcourse/${this.examInfo.id}`;
	  	get(url)
	  	.then(res => {
	  		if(res.code==200){
	  			this.imgarray = [...res.data.templateImages,...this.imgarray]
				this.$emit('imageurllist',this.imgarray)
				this.onlinetemplate = res.data.templateImages
	  		}
	  	})
	  	.catch(error => {
	  		 this.$message.error(error.message); 
	  	});
	  },
	  onEnd(event) {
		const newIndex = event.newIndex;
			  // 更新拖拽元素的 page 值
		this.imgarray.forEach((image, index) => {
		        image.page = index + 1; // 更新 page 属性为新的索引值加 1
	   })
	   this.$emit('image-uploaded', this.imgarray);
		// //console.info(this.imgarray)
	  },
		  onMoveCallback(list){
			  // //console.info(this.imgarray)
			  // //console.info(list)
		  },
    handleFileChange(event) {
		if(this.examNoLength!=0&&this.answerCardPages!=0){
			const loading = this.$loading({
									lock: true,
									text: 'Loading',
									spinner: 'el-icon-loading',
									background: 'rgba(0, 0, 0, 0.7)'
								});
			const file = event.target.files;
			if (file && file.length > 0) {
					  Array.from(file).forEach((file, index) => {
						  post('/template/upload', {file:file}, {
						    headers: {
						      'Content-Type': 'multipart/form-data',
						    }
						  })
						  .then(res => {
						    if(res.code==200){
								const imgObj = {
										imageUrl: res.data,
										page: index + 1,
										id:index
								  }
						  	  this.imgarray.push(imgObj)
						  	  this.$emit('image-uploaded', this.imgarray);
									loading.close();
						    }else{
						  	 this.$message.error(res.message); 
						    }
						  })
						  .catch(error => {
						  	this.$message.error(error.message);
						  });
					  })
			  // this.imageUrl = URL.createObjectURL(file);
			}
		}else{
			this.$message.error('请填写考号位数或答题卡页数');
		}	
    },
	delecttemplate(id){
		const index = this.imgarray.findIndex(item => item.id === id);
		// 如果找到了目标元素，则使用 splice 方法删除
		if (index !== -1) {
		  this.imgarray.splice(index, 1);
		}
		
		// let url = `/template/image/${id}`
		// del(url)
		// .then(res=>{
		// 	//console.info(res)
		// 	this.imgarray=[]
		// 	this.modeltab()
		// })
		// .catch(error=>{
			
		// })
		// del('/template',{templateId:id})
		// .then(res=>{
		// 	//console.info(res)
		// 	this.modeltab()
		// })
		// .catch(error=>{
			
		// })
	}
  },
 //  beforeDestroy() {
 //  	if(this.onlinetemplate.length!=this.imgarray.length){
	// 	this.$confirm('有未保存的操作，是否继续', '提示', {
	// 	  confirmButtonText: '确定',
	// 	  cancelButtonText: '取消',
	// 	  type: 'warning'
	// 	}).then(() => {
	// 	 //  this.$message({
	// 		// type: 'success',
	// 		// message: '删除成功!'
	// 	 //  });
	// 	}).catch(() => {
	// 		this.$router.go(-1)
	// 	 //  this.$message({
	// 		// type: 'info',
	// 		// message: '已取消'
	// 	 //  });          
	// 	});
	// }
 //  }
};
</script>

<style scoped>
	.uploadlist{
		display: flex;
		align-items: center;
	}
.upload-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  position:relative;
  width:200px;
  height:140px;
  margin:22px 0;
}

.image-preview {
}

.image-preview img {
  width:200px;
 height:140px;
}
.uploadBoxinfo{
	box-sizing: border-box;
	width: 200px;
	height: 140px;
	background: #FFFFFF;
	border-radius: 10px;
	border: 1px dashed #D8E4F0;
	text-align: center;
	padding-top:28px;
	font-size:16px;
	color:#295CFF;
	cursor: pointer;
	position:absolute;
	z-index:1;
}
.uploadBoxinfo i{
	display:block;
	color:#D8E4F0;
	padding:5px 0;
}
.fileIndex{
	position:absolute;
	left:0;
	top:0;
	width:100%;
	height:100%;
	z-index:2;
	cursor: pointer;
	opacity: 0;
}
.imgmove span{
	display: flex;
	align-items: center;
	margin:0 13px;
}
.imgmove span div{
	margin:0 13px;
}
.boxsetdelecte{
	position:relative;
}
.boxsetdelecte span{
	position:absolute;
	left:-24px;
	top:24px;
}
.buttonboxedit{
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top:5px;
}
.buttonboxedit i{
	width: 52px;
	height: 24px;
	background: #295cff1a;
	border-radius: 12px;
	font-size: 16px;
	color: #295CFF;
	text-align: justify;
	line-height:24px;
	text-align: center;
	font-style:normal;
	cursor: pointer;
}
.buttonboxedit i:last-child{
	background: #ec555a1a;
	color:#EC555A;
	margin-left:15px;
}
.boxsetdelecte b{
	display: block;
	text-align: center;
	font-size:20px;
	padding-bottom:6px;
}
</style>